package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Picture;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.ActivityDao;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;
import cn.edu.seu.herald.informationplatform.dao.database.PictureDao;

public class PictureDelete extends HttpServlet {

	private static final boolean SUCCESS = true;

	private static final boolean FAILURE = false;

	private static final String SUCCESS_MESSAGE = "操作成功";

	private static final String FAILURE_MESSAGE = "操作失败";

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		try {
			int pictureId = Integer.valueOf(request.getParameter("picture"));
			PictureDao dao = PictureDao.getDao();
			Picture picture = dao.getPictureById(pictureId);
			String path = getServletContext().getRealPath("/");
			String rawRealPath = path+picture.getAddress();
			Properties pro = System.getProperties();
	        String osName = pro.getProperty("os.name");
	        File file = null;
	        System.out.println(rawRealPath);
	        if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
	        	file = new File(rawRealPath);  
	        }else{
	        	file = new File(rawRealPath.replaceAll("\\\\", "/"));
	        }
			
			
		    if (file.isFile() && file.exists()) {  
		        file.delete();  
		    }  
			dao.deletePicture(pictureId);
			LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			String albumId=request.getParameter("albumId");
			response.sendRedirect("./album.jsp?league="+luSessionCookieAccess.getLeagueId()+"&album="+albumId);
			
		} catch (SQLException e) {
			printResult(response, FAILURE);
			return;
		} catch (NumberFormatException e) {
			printResult(response, FAILURE);
			return;
		} catch (SessionIdNotFound e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		printResult(response, SUCCESS);
	}
	
	private void printResult(HttpServletResponse response,
			boolean success) throws IOException {
		response.getWriter().println((success) ?
				SUCCESS_MESSAGE : FAILURE_MESSAGE);
	}

}
